//
//  HeartaxDetailController.m
//  caishuitong
//
//  Created by qiysoft on 2017/4/12.
//  Copyright © 2017年 zhangxy. All rights reserved.
//

#import "HeartaxDetailController.h"
#import "HeartaxDetailCellA.h"
#import "HeartaxDetailCellB.h"
#import "HeartaxDetailModel.h"
#import "LoginViewController.h"
#import "AFNetworking.h"
#import "NSString+AttributedString.h"
#import "HHBaseLoadToken.h"
#import "AudioPlayerManage.h"
#import "AppDelegate.h"
#import "UIImageView+WebCache.h"

#define HeartaxDetailCellAIndentifier @"HeartaxDetailCellAIndentifier"
#define HeartaxDetailCellBIndentifier @"HeartaxDetailCellBIndentifier"

@interface HeartaxDetailController ()<UITableViewDataSource,UITableViewDelegate,HeartaxDetailCellADelegate,TermCellDelegate,AudioPlayerManageDelegate,UITextViewDelegate>{

    BOOL isA;
    NSMutableAttributedString *attrStr;
    NSString *conts;
    CGFloat textViewH;
    NSURL *url;
}

@property (nonatomic ,strong) HeartaxDetailModel *heartaxDetailModel;
@property (nonatomic ,strong) NSMutableArray *heartaxDetailArr;// 总数据数组
@property (nonatomic ,assign) int j;

@property (nonatomic, assign) float progress;
@property (nonatomic, copy) NSString * playTime;
@property (nonatomic, copy) NSString * playDuration;
@property (nonatomic, strong) HeartaxDetailCellA *cell;
@property (nonatomic, strong) HeartaxDetailCellB *cell1;

@property (weak, nonatomic) IBOutlet UILabel *lbCollect;
@property (weak, nonatomic) IBOutlet UILabel *lbSupport;
@property (weak, nonatomic) IBOutlet UILabel *lbComment;
@property (weak, nonatomic) IBOutlet UILabel *lbShare;
@property (weak, nonatomic) IBOutlet UIButton *btnSupport;
@property (weak, nonatomic) IBOutlet UIButton *btnCollect;

@end

@implementation HeartaxDetailController

// -----------------------------------
//1.采取以下方式不影响其他的界面的侧滑手势。
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    // 禁用返回手势
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = NO;

    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    
    AudioPlayerManage *playerManage = [AudioPlayerManage playerManage];
    
    self.delegate = playerManage;
    playerManage.delegatePlayer = self;
    [appDelegate.wWindow dissmissWindow];
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    AudioPlayerManage *playerManage = [AudioPlayerManage playerManage];
    [playerManage audioPlayerPause];
    [playerManage audioPlayerDestroy];
//    if ([WShareUtil sharedData].isPlay) {
//        [WShareUtil sharedData].isShowTool = YES;
//    }else {
//        [WShareUtil sharedData].isShowTool = NO;
//    }
//
//    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
//    if ([WShareUtil sharedData].isShowTool) {
//
//        [appDelegate.wWindow showWindow];
//
//        if ([WShareUtil sharedData].isHeartaxList) {
//            [WShareUtil sharedData].isHeartaxList = NO;
//        }else {
//
//            if ([url.absoluteString isEqualToString:_strUrl]) {
//                [playerManage audioPlayerPause];
//                [playerManage audioPlayerDestroy];
//                [appDelegate.wWindow dissmissWindow];
//            }
//        }
//    }else {
//        [appDelegate.wWindow dissmissWindow];
//    }

    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    }
}

// 查看更多
- (void)lookBtn:(UIButton *)button {
    isA = !isA;
    [self tableView:_myTableView heightForRowAtIndexPath:[NSIndexPath indexPathWithIndex:1]];
    [_myTableView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    isA = YES;

    _heartaxDetailArr = [NSMutableArray array];
    self.lbComment.textColor = WRGBColor(93, 93, 93);
    self.lbShare.textColor = WRGBColor(93, 93, 93);
    self.lbSupport.textColor = WRGBColor(93, 93, 93);
    self.lbCollect.textColor = WRGBColor(93, 93, 93);
    self.playTime = [NSString stringWithFormat:@"%@",@"0"];
    self.title = @"每日听税";
    
    // 1.注册控件
    UINib *cellNib = [UINib nibWithNibName:@"HeartaxDetailCellA" bundle:nil];
    [self.myTableView registerNib:cellNib forCellReuseIdentifier:HeartaxDetailCellAIndentifier];
    _myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    self.prototypeCell  = [self.myTableView dequeueReusableCellWithIdentifier:HeartaxDetailCellAIndentifier];
    
    UINib *cellNib1 = [UINib nibWithNibName:@"HeartaxDetailCellB" bundle:nil];
    [self.myTableView registerNib:cellNib1 forCellReuseIdentifier:HeartaxDetailCellBIndentifier];
    self.prototypeCell  = [self.myTableView dequeueReusableCellWithIdentifier:HeartaxDetailCellBIndentifier];
    
    _j = 1;
    WLog(@"_strId%@",_strId);

    if ([WShareUtil sharedData].dicSession) {
        [self requestCollectOrSupportState:[WShareUtil getServerURL:queryArticleMetaInfo]];
    }
    [self requestListDataStrNum:@"1" isRefresh:YES]; // 下载详情数据
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(noPlay) name:@"NOPLAY" object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stopPlay) name:@"STOPPLAY" object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playToggleClick) name:PLAYTOGGLE object:nil];

}

- (void)playToggleClick {
    [self.myTableView reloadData];
}

- (void)stopPlay {
    AudioPlayerManage *playerManage = [AudioPlayerManage playerManage];
    [playerManage audioPlayerPause];
}

- (void)noPlay {
    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    [appDelegate.wWindow.playTool.btnPlay setImage:[UIImage imageNamed:@"Toolplay"] forState:UIControlStateNormal];
    appDelegate.wWindow.playTool.btnPlay.selected = NO;
}

- (void)alertWithMsg:(NSString *)msg
{
    [[[UIAlertView alloc] initWithTitle:@"温馨提示：" message:msg delegate:nil cancelButtonTitle:@"确 定" otherButtonTitles:nil, nil] show];
}

- (void)requestListDataStrNum:(NSString *)pageNum isRefresh:(BOOL)isRefresh{
    if ([WShareUtil strNilOrEmpty:[WShareUtil sharedData].strToken]) {
        HHBaseLoadToken *loadToken = [[HHBaseLoadToken alloc] init];// 获取Token （目前先：token过期后，获取一次就关掉）
        [loadToken loadToken];
        loadToken.tokenBlock = ^(NSString *strToken) {
            if (![WShareUtil strNilOrEmpty:strToken]) {
                [self requestListDataStrNum:pageNum isRefresh:isRefresh];
            }else {
                WLog(@"没有token");
            }
        };
        WLog(@"%@",[WShareUtil sharedData].strToken);
    }else {

        NSString *userId;
        if ([WShareUtil sharedData].dicSession) {
            userId = @"141978";
            if (userId == nil) {
                userId = @"";
            }

        }else {
            userId = @"";
        }
        NSString *uuid= @"e1e1e1";
        NSDictionary *parametersDict;
        parametersDict = @{@"jqbh":uuid,@"token":[WShareUtil sharedData].strToken,@"id":_strId,@"userid":userId};

        // 字典转JSON字符串
        NSString *jsonData = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:parametersDict]];

        // 加密JSON字符串
        WLog(@"加密JSON字符串的结果%@",[CommonFunc encryptWithText:jsonData]);//加密方法
        WLog(@"解密乱码后的结果%@",[CommonFunc decryptWithText:@"sZjh+Dfxf1kcn5u4bgq4g75bHbBQ6DlL2oF3ELtxXb8dkwb1w5GRyfm7huCriDvlsdsFDoOWLqzX7tt+NpCuiEApxy+2QONMEZpGLBejk+1ZPreDtd3O7Q=="]);//解密方法

        // 加密后字典参数
        NSDictionary *paramsDic = @{@"params":[CommonFunc encryptWithText:jsonData]};

        [WHttpTool POST:@"http://mobile.csfw360.com:18082/csfw_jiekou/hyfw/ts/tsDetail" parameters:paramsDic success:^(id responseObject) {
            NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
            NSDictionary *JsonDic = [WHttpTool dictionaryWithJsonString:responseStr];
            NSString *messageStr = [JsonDic objectForKey:@"message"];
            NSString *successStr= [JsonDic objectForKey:@"success"];
            // 解密请求回的数据（字典）
            [CommonFunc decryptWithText:messageStr];
            NSString *returnStr = [CommonFunc decryptWithText:messageStr];
            // json字符串转字典
            NSDictionary *returnDic = [WHttpTool dictionaryWithJsonString:returnStr];

            if ([returnDic[@"resultCode"] isEqualToString:@"EC0001"] || [returnDic[@"resultCode"] isEqualToString:@"EC0002"] ) {
                HHBaseLoadToken *loadToken = [[HHBaseLoadToken alloc] init];// 获取Token （目前先：token过期后，获取一次就关掉）
                [loadToken loadToken];
                loadToken.tokenBlock = ^(NSString *strToken) {
                    if (![WShareUtil strNilOrEmpty:strToken]) {
                        [self requestListDataStrNum:pageNum isRefresh:isRefresh];
                    }else {

                        [WShareUtil showAlert:@"温馨提示" message:@"没有token"];

                        return ;

                        WLog(@"没有token");
                    }
                };

                WLog(@"%@====",[WShareUtil sharedData].strToken);
            }else if([returnDic[@"resultCode"] isEqualToString:@"EC0005"]){

                [WShareUtil showAlert:@"温馨提示" message:@"您的服务已经到期"];
                return ;

            }else if([returnDic[@"resultCode"] isEqualToString:@"EC0006"]){

                [WShareUtil showAlert:@"温馨提示" message:@"您被禁止登录"];
                return ;

            }else if([returnDic[@"resultCode"] isEqualToString:@"EC0008"]){

                UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您的账号可能在其他设备登录,请重新登录！" delegate:self cancelButtonTitle:nil otherButtonTitles:@"好的", nil];
                [alertView show];

                [WShareUtil sharedData].dicSession = nil;
                return ;
                WLog(@"没有用户");

            }

            if (isRefresh) {
                [self.heartaxDetailArr removeAllObjects];
            }

            _heartaxDetailModel = [HeartaxDetailModel mj_objectWithKeyValues:returnDic];

            [self.heartaxDetailArr addObject:_heartaxDetailModel];

            [[self myTableView] reloadData];
        } failure:^(NSError *error) {
            WLog(@"请求失败");

        } showProgress:YES];
    }
}

//设置UITableViewCell的数据
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        
        _cell = [[self myTableView] dequeueReusableCellWithIdentifier: HeartaxDetailCellAIndentifier];
        _cell.selectionStyle = UITableViewCellSelectionStyleNone;
        _cell.lbPlayTime.text = @"00:00";
        _cell.lbTotalTime.text = @"00:00";
        _cell.delegateHeartax = self;
        [_cell.btnPlay setImage:[UIImage imageNamed:@"playDetail"] forState:UIControlStateNormal];

        _cell.sliderCell.enabled = NO;
        [_cell.sliderCell addTarget:self action:@selector(getValue:) forControlEvents:UIControlEventValueChanged];
        if (self.heartaxDetailArr.count > 0 && self.heartaxDetailArr != nil) {
            _cell.titleLB.text = [self.heartaxDetailArr[indexPath.row]title];

            NSString *strUrl =  [[self.heartaxDetailArr[indexPath.row] strImgUrl] stringByReplacingOccurrencesOfString:@"\\" withString:@"/"];

            strUrl = [NSString stringWithFormat:@"http://www.csfw360.com%@",strUrl];
            [_cell.imageCell sd_setImageWithURL:[NSURL URLWithString:strUrl] placeholderImage:[UIImage imageNamed:@"heartaxbg.png"]];

        }
        return _cell;
        
    }else if (indexPath.section == 1){
        
        _cell1  = [[self myTableView] dequeueReusableCellWithIdentifier: HeartaxDetailCellBIndentifier];
        _cell1.selectionStyle = UITableViewCellSelectionStyleNone;
        _cell1.delegate = self;// 查看更多的代理回调
        if (self.heartaxDetailArr.count > 0 && self.heartaxDetailArr != nil) {
            _cell1.titleLBB.text = [self.heartaxDetailArr[indexPath.row]title];
            _cell1.cjsjLB.text = [WShareUtil timeFormat:[self.heartaxDetailArr[indexPath.row] cjsj]];//或cjsj//createTime
            _cell1.playTimesLB.text = [NSString stringWithFormat:@"%@次播放",[self.heartaxDetailArr[indexPath.row] playTimes]];// 播放次数？
//            _cell1.lbtime.text = @"00:00";
            if (isA) {
                conts = [[self.heartaxDetailArr[indexPath.row] content] substringToIndex:240];//截取掉下标7之后的字符串
            }else{
                conts = [self.heartaxDetailArr[indexPath.row] content];
            }
            //设置富文本显示，
//            _cell1.contentLB.attributedText = [conts stringWithParagraphlineSpeace:26 textColor:[UIColor greenColor] textFont:[UIFont systemFontOfSize:15]];
            
            // ---------- 设置textView的行间距
            NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
            paragraphStyle.lineSpacing = 8;// 字体的行间距
            
            NSDictionary *attributes = @{
                                         NSFontAttributeName:[UIFont systemFontOfSize:15],
                                         NSKernAttributeName:@1.5f,
                                         NSParagraphStyleAttributeName:paragraphStyle
                                         };
            
            // 显示带标签的文字
            attrStr = [[NSMutableAttributedString alloc] initWithData:[conts dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:&attributes error:nil];
            
            [attrStr addAttributes:@{NSParagraphStyleAttributeName:paragraphStyle,NSKernAttributeName:@1.5f,NSFontAttributeName:[UIFont systemFontOfSize:15]} range:NSMakeRange(0, attrStr.length)];
            
            _cell1.contentLB.attributedText = attrStr;
            _cell1.contentLB.font = [UIFont systemFontOfSize:15];
            _cell1.contentLB.editable = NO;
            
            CGRect frameL = _cell1.playTimesLB.frame;
            CGRect frame = CGRectMake(3, frameL.origin.y + frameL.size.height + 10, WSCREENH_WIDTH - 5, 180);

            CGSize size = [_cell1.contentLB.text sizeWithFont:_cell1.contentLB.font
                                                    constrainedToSize:CGSizeMake(WSCREENH_WIDTH - 5, MAXFLOAT)
                                                        lineBreakMode:NSLineBreakByTruncatingTail];
            
            if (frame.size.height > 50) {
                frame.size.height = size.height ;
            }else {
                frame.size.height = 40;
            }
            _cell1.contentLB.frame = frame;
            [self textViewDidChange:_cell1.contentLB];
            _cell1.contentLB.delegate = self;

            
            if ([WShareUtil strNilOrEmpty:_cell1.contentLB.text]) {
                _cell1.contentLB.text = @"";
            }            
            _cell1.contentLB.textColor = [UIColor colorWithRed:0.4 green:0.4 blue:0.4 alpha:1];
//            _cell1.contentLB.backgroundColor = [UIColor redColor];
        }
        return _cell1;
    }
    return nil;
}

- (void)textViewDidChange:(UITextView *)textView
{
    if (isA) {
        textViewH = 365;
    }else {
        CGRect rect = textView.frame;
        rect.size.height = textView.contentSize.height;
        textView.frame = rect;
        
        textViewH = textView.frame.size.height;

        if ([WShareUtil strNilOrEmpty:textView.text] || [textView.text length] <= 0) {
            textViewH = 0;
        }
    }
    [textView scrollRangeToVisible:NSMakeRange(0,0)];
}


-(void)getValue:(id)sender{
    UISlider *sli2=(UISlider *)sender;
    if (sli2.value >= 0.99) {
        sli2.value = 0.9990;
    }
    if (self.delegate && [self.delegate respondsToSelector:@selector(changeSliderValueClicked:)]) {
        [self.delegate changeSliderValueClicked:sender];
    }
}

//行点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

//分组个数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

//列表行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }else{
        return 1;
    }
}

//设置行高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        
        return 350;
    }else{
        // 展开收起时返回不同的行高
        if (isA) {
            
            if ([WShareUtil strNilOrEmpty:conts] || [conts length] <= 0) {
                return 170;
            }
            return 370;
        }else{
            if (self.heartaxDetailArr.count <= 0 || self.heartaxDetailArr == nil) {
                return 170;
            }
            
            if (iOS10) {
                if (iPhone6_6s) {
                    return 180 + textViewH;
                }else if (iPhone6Plus_6sPlus) {
                    return 180 + textViewH;
                }else if (XIPHONE) {
                    return 180 + textViewH;
                }else {
                    return 180 + textViewH;
                }
            }
            
            if (iPhone6_6s) {
                return 180 + textViewH;
            }else if (iPhone6Plus_6sPlus) {
                return 180 + textViewH;
            }else {
                return 180 + textViewH;
            }
        }
    }
}

- (IBAction)btnA:(UIButton *)sender {
    // 收藏
    sender.selected = !sender.selected;
    if (sender.selected) {

        [self requestData:[WShareUtil getServerURL:optArticle] support:@"shC"];
    }else {

        [self requestData:[WShareUtil getServerURL:optArticle] support:@"qxShC"];
    }
    
}

- (IBAction)btnB:(UIButton *)sender {

    sender.selected = !sender.selected;
    if (sender.selected) {
       
        [self requestData:[WShareUtil getServerURL:optArticle] support:@"dz"];
    }else {
        [self requestData:[WShareUtil getServerURL:optArticle] support:@"qxdz"];
    }
}

- (IBAction)btnC:(id)sender {

}

- (IBAction)btnD:(id)sender {

}

- (void)requestData:(NSString *)url support:(NSString *)support{

    if ([WShareUtil strNilOrEmpty:[WShareUtil sharedData].strToken]) {
        HHBaseLoadToken *loadToken = [[HHBaseLoadToken alloc] init];// 获取Token （目前先：token过期后，获取一次就关掉）
        [loadToken loadToken];
        loadToken.tokenBlock = ^(NSString *strToken) {
            if (![WShareUtil strNilOrEmpty:strToken]) {
                [self requestData:url support:support];
            }else {
                WLog(@"没有token");
            }
        };
    }else {

        if ([WShareUtil sharedData].dicSession) {
            NSString *uuid= @"e1e1e1";
            // type 听税 1 其他是 2
            NSString *userId = @"141978";
            ;
            NSDictionary *parametersDict = @{@"jqbh":uuid,@"token":[WShareUtil sharedData].strToken,@"optionname":support,@"type":@"1",@"article_id":_strId,@"userid":userId,@"app_type":@"2"};
            // 字典转JSON字符串
            NSString *jsonData = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:parametersDict]];

            // 加密JSON字符串
            WLog(@"加密JSON字符串的结果%@",[CommonFunc encryptWithText:jsonData]);//加密方法
            WLog(@"解密乱码后的结果%@",[CommonFunc decryptWithText:@"sZjh+Dfxf1kcn5u4bgq4g75bHbBQ6DlL2oF3ELtxXb8dkwb1w5GRyfm7huCriDvlsdsFDoOWLqzX7tt+NpCuiEApxy+2QONMEZpGLBejk+1ZPreDtd3O7Q=="]);//解密方法

            // 加密后字典参数
            NSDictionary *paramsDic = @{@"params":[CommonFunc encryptWithText:jsonData]};

            [WHttpTool POST:url parameters:paramsDic success:^(id responseObject) {
                NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
                NSDictionary *JsonDic = [WHttpTool dictionaryWithJsonString:responseStr];
                NSString *messageStr = [JsonDic objectForKey:@"message"];
                NSString *successStr= [JsonDic objectForKey:@"success"];
                // 解密请求回的数据（字典）
                [CommonFunc decryptWithText:messageStr];
                NSString *returnStr = [CommonFunc decryptWithText:messageStr];
                // json字符串转字典
                NSDictionary *returnDic = [WHttpTool dictionaryWithJsonString:returnStr];

                if ([returnDic[@"resultCode"] isEqualToString:@"EC0001"] || [returnDic[@"resultCode"] isEqualToString:@"EC0002"] ) {
                    HHBaseLoadToken *loadToken = [[HHBaseLoadToken alloc] init];// 获取Token （目前先：token过期后，获取一次就关掉）
                    [loadToken loadToken];
                    loadToken.tokenBlock = ^(NSString *strToken) {
                        if (![WShareUtil strNilOrEmpty:strToken]) {
                            [self requestData:url support:support];
                        }else {

                            [WShareUtil showAlert:@"温馨提示" message:@"没有token"];

                            return ;

                            WLog(@"没有token");
                        }
                    };

                    WLog(@"%@====",[WShareUtil sharedData].strToken);
                }else if([returnDic[@"resultCode"] isEqualToString:@"EC0005"]){

                    [WShareUtil showAlert:@"温馨提示" message:@"您的服务已经到期"];
                    return ;

                }else if([returnDic[@"resultCode"] isEqualToString:@"EC0006"]){

                    [WShareUtil showAlert:@"温馨提示" message:@"您被禁止登录"];
                    return ;

                }else if([returnDic[@"resultCode"] isEqualToString:@"EC0008"]){

                    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您的账号可能在其他设备登录,请重新登录！" delegate:self cancelButtonTitle:nil otherButtonTitles:@"好的", nil];
                    [alertView show];

                    [WShareUtil sharedData].dicSession = nil;
                    return ;
                    WLog(@"没有用户");

                }

                if ([returnDic[@"isfavorites"] boolValue]) {
                    self.lbCollect.textColor = WRGBColor(47, 135, 212);

                    [self.btnCollect setImage:[UIImage imageNamed:@"collect_pre.png"] forState:UIControlStateNormal];
                    self.btnCollect.selected = YES;
                }else {
                    self.lbCollect.textColor = WRGBColor(93, 93, 93);

                    [self.btnCollect setImage:[UIImage imageNamed:@"collect.png"] forState:UIControlStateNormal];
                    self.btnCollect.selected = NO;

                }


                if ([returnDic[@"isup"] boolValue]) {
                    _lbSupport.textColor = WRGBColor(47, 135, 212);

                    [_cell.btnSupport setImage:[UIImage imageNamed:@"likebutton_pre.png"] forState:UIControlStateNormal];
                    [_btnSupport setImage:[UIImage imageNamed:@"likebutton_pre@2x.png"] forState:UIControlStateNormal];
                    _cell.btnSupport.selected = _btnSupport.selected = YES;
                }else {

                    _lbSupport.textColor = WRGBColor(93, 93, 93);

                    [_cell.btnSupport setImage:[UIImage imageNamed:@"likebutton.png"] forState:UIControlStateNormal];
                    [_btnSupport setImage:[UIImage imageNamed:@"likebutton.png"] forState:UIControlStateNormal];
                    _cell.btnSupport.selected = _btnSupport.selected = NO;
                }

            } failure:^(NSError *error) {
                WLog(@"请求失败");

            } showProgress:YES];

        }else {

            [SVProgressHUD showImage:nil status:@"请先登录"];
            [SVProgressHUD setOffsetFromCenter:UIOffsetMake(0, WSCREENH_HEIGHT *0.5 - 70)];
            [SVProgressHUD dismissWithDelay:1.];
            [SVProgressHUD setBackgroundColor:[UIColor colorWithRed:0.9 green:0.91 blue:0.93 alpha:1]];   //背景颜色
        }
    }
}

- (void)btnOfHeartaxClicked:(UIButton *)sender {
    
    AudioPlayerManage *playerManage = [AudioPlayerManage playerManage];
    
    if ([WShareUtil strNilOrEmpty:_strUrl]) {
        
        NSString *strUrl =  [self.heartaxDetailModel.audio_src stringByReplacingOccurrencesOfString:@"\\" withString:@"/"];
        playerManage.currentUrl = strUrl;
        playerManage.currentIndex = -1;
        
    }else {
        playerManage.currentUrl = _strUrl;
        playerManage.currentIndex = _currentIndex;
    }
    
    NSMutableDictionary *dicM = [NSMutableDictionary dictionary];
    dicM[@"title"] = [self.heartaxDetailModel title];
    dicM[@"audio_src"] = playerManage.currentUrl;
    dicM[@"audio_id"] = [self.heartaxDetailModel ID];
    [WShareUtil sharedData].playerModel = [PlayerModel mj_objectWithKeyValues:dicM];
    
    if (sender.tag == 100) {
        [self.navigationController popViewControllerAnimated:YES];
    }else if (sender.tag == 101) {
        
        if ([WShareUtil sharedData].isPlay) {
            [playerManage audioPlayerSeekTime:-5];
        }

    }else if (sender.tag == 102) {

        self.cell.sliderCell.enabled = YES;
        sender.selected = !sender.selected;
        
        [WShareUtil sharedData].isShowTool = YES;
        if (sender.selected) {
            [sender setImage:[UIImage imageNamed:@"pause"] forState:UIControlStateNormal];

            BOOL isWWAN = [[NSUserDefaults standardUserDefaults] boolForKey:@"isWWAN"];

//            if (kIs3GOr4GNetwork && !isWWAN) {
//                [MBProgressHUD showError:@"请打开我的页面，选择设置中心打开2/3/4G播放开关" toView:[HHBaseViewHelp findViewController:nil].view];
//                return;
//
//            }else {
                [playerManage audioPlayerPlay];
//            }
        }else {
            [sender setImage:[UIImage imageNamed:@"playDetail"] forState:UIControlStateNormal];
            [playerManage audioPlayerPause];
        }
        
        [playerManage setPlayFinishBlock:^(BOOL isFinish){
            if (isFinish) {
                WLog(@"完成");
            }
        }];
        
    }else if (sender.tag == 103) {
        
        if ([WShareUtil sharedData].isPlay) {
            [playerManage audioPlayerSeekTime:5];
        }
    
    }else if (sender.tag == 104) {
        
        NSString *dzOrQx;

        if ([WShareUtil sharedData].dicSession) {
            sender.selected = !sender.selected;
            
            if (sender.selected) {
                dzOrQx = @"dz";
                [sender setImage:[UIImage imageNamed:@"likebutton.png"] forState:UIControlStateNormal];
            }else {
                dzOrQx = @"qxdz";
                [sender setImage:[UIImage imageNamed:@"likebutton_pre.png"] forState:UIControlStateNormal];
            }
        }
        [self requestData:[WShareUtil getServerURL:optArticle] support:dzOrQx];
    }
}

#pragma mark - 私有方法
- (NSString *)convertStringWithTime:(float)time {
    if (isnan(time)) time = 0.f;
    int min = time / 60.0;
    int sec = time - min * 60;
    NSString * minStr = min > 9 ? [NSString stringWithFormat:@"%d",min] : [NSString stringWithFormat:@"0%d",min];
    NSString * secStr = sec > 9 ? [NSString stringWithFormat:@"%d",sec] : [NSString stringWithFormat:@"0%d",sec];
    NSString * timeStr = [NSString stringWithFormat:@"%@:%@",minStr, secStr];
    return timeStr;
}

// 请求点赞收藏状态
- (void)requestCollectOrSupportState:(NSString *)url {

    if ([WShareUtil strNilOrEmpty:[WShareUtil sharedData].strToken]) {
        HHBaseLoadToken *loadToken = [[HHBaseLoadToken alloc] init];// 获取Token （目前先：token过期后，获取一次就关掉）
        [loadToken loadToken];
        loadToken.tokenBlock = ^(NSString *strToken) {
            if (![WShareUtil strNilOrEmpty:strToken]) {
                [self requestCollectOrSupportState:url];
            }else {
                WLog(@"没有token");
            }
        };
        WLog(@"%@",[WShareUtil sharedData].strToken);
    }else {
        // type 听税 1 其他是 2
        NSString *userId = @"141978";
        NSDictionary *parametersDict;
        NSString *uuid= @"e1e1e1";
        if ([WShareUtil strNilOrEmpty:userId]) {
            parametersDict = @{@"jqbh":uuid,@"token":[WShareUtil sharedData].strToken,@"type":@"1",@"article_id":_strId};

        }else {
            parametersDict = @{@"jqbh":uuid,@"token":[WShareUtil sharedData].strToken,@"type":@"1",@"article_id":_strId,@"userid":userId};
        }
        // 字典转JSON字符串
        NSString *jsonData = [NSString stringWithFormat:@"%@",[WHttpTool convertToJsonData:parametersDict]];

        // 加密JSON字符串
        WLog(@"加密JSON字符串的结果%@",[CommonFunc encryptWithText:jsonData]);//加密方法
        WLog(@"解密乱码后的结果%@",[CommonFunc decryptWithText:@"sZjh+Dfxf1kcn5u4bgq4g75bHbBQ6DlL2oF3ELtxXb8dkwb1w5GRyfm7huCriDvlsdsFDoOWLqzX7tt+NpCuiEApxy+2QONMEZpGLBejk+1ZPreDtd3O7Q=="]);//解密方法

        // 加密后字典参数
        NSDictionary *paramsDic = @{@"params":[CommonFunc encryptWithText:jsonData]};

        [WHttpTool POST:url parameters:paramsDic success:^(id responseObject) {
            NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
            NSDictionary *JsonDic = [WHttpTool dictionaryWithJsonString:responseStr];
            NSString *messageStr = [JsonDic objectForKey:@"message"];
            NSString *successStr= [JsonDic objectForKey:@"success"];
            // 解密请求回的数据（字典）
            [CommonFunc decryptWithText:messageStr];
            NSString *returnStr = [CommonFunc decryptWithText:messageStr];
            // json字符串转字典
            NSDictionary *returnDic = [WHttpTool dictionaryWithJsonString:returnStr];

            if ([returnDic[@"resultCode"] isEqualToString:@"EC0001"] || [returnDic[@"resultCode"] isEqualToString:@"EC0002"] ) {
                HHBaseLoadToken *loadToken = [[HHBaseLoadToken alloc] init];// 获取Token （目前先：token过期后，获取一次就关掉）
                [loadToken loadToken];
                loadToken.tokenBlock = ^(NSString *strToken) {
                    if (![WShareUtil strNilOrEmpty:strToken]) {
                        [self requestCollectOrSupportState:url];
                    }else {

                        [WShareUtil showAlert:@"温馨提示" message:@"没有token"];

                        return ;

                        WLog(@"没有token");
                    }
                };

                WLog(@"%@====",[WShareUtil sharedData].strToken);
            }else if([returnDic[@"resultCode"] isEqualToString:@"EC0005"]){

                [WShareUtil showAlert:@"温馨提示" message:@"您的服务已经到期"];
                return ;

            }else if([returnDic[@"resultCode"] isEqualToString:@"EC0006"]){

                [WShareUtil showAlert:@"温馨提示" message:@"您被禁止登录"];
                return ;

            }else if([returnDic[@"resultCode"] isEqualToString:@"EC0008"]){

                UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您的账号可能在其他设备登录,请重新登录！" delegate:self cancelButtonTitle:nil otherButtonTitles:@"好的", nil];
                [alertView show];

                [WShareUtil sharedData].dicSession = nil;
                return ;
                WLog(@"没有用户");

            }

            if ([returnDic[@"isfavorites"] boolValue]) {

                [self.btnCollect setImage:[UIImage imageNamed:@"collect_pre.png"] forState:UIControlStateNormal];
                self.btnCollect.selected = YES;
                self.lbCollect.textColor = WRGBColor(47, 135, 212);
            }else {
                [self.btnCollect setImage:[UIImage imageNamed:@"collect.png"] forState:UIControlStateNormal];
                self.btnCollect.selected = NO;

                self.lbCollect.textColor = WRGBColor(93, 93, 93);
            }

            if ([returnDic[@"isup"] boolValue]) {
                [self.btnSupport setImage:[UIImage imageNamed:@"likebutton_pre.png"] forState:UIControlStateNormal];

                [_cell.btnSupport setImage:[UIImage imageNamed:@"likebutton_pre@2x.png"] forState:UIControlStateNormal];

                _cell.btnSupport.selected = YES;
                self.btnSupport.selected = YES;
                self.lbSupport.textColor = WRGBColor(47, 135, 212);

            }else {

                [self.btnSupport setImage:[UIImage imageNamed:@"likebutton.png"] forState:UIControlStateNormal];

                self.btnSupport.selected = NO;

                self.lbSupport.textColor = WRGBColor(93, 93, 93);
                [_cell.btnSupport setImage:[UIImage imageNamed:@"likebutton.png"] forState:UIControlStateNormal];

                _cell.btnSupport.selected = NO;
            }

        } failure:^(NSError *error) {
            WLog(@"请求失败");

        } showProgress:YES];
    }
}

-(NSURL *)urlOfCurrentlyPlayingInPlayer:(AVPlayer *)player{
    // get current asset
    AVAsset *currentPlayerAsset = player.currentItem.asset;
    // make sure the current asset is an AVURLAsset
    if (![currentPlayerAsset isKindOfClass:AVURLAsset.class]) return nil;
    // return the NSURL
    return [(AVURLAsset *)currentPlayerAsset URL];
}

- (void)changeUIstateClicked:(AVPlayer *)player {
    

    if ([WShareUtil strNilOrEmpty:_strUrl]) {
        
         NSString *strUrl =  [self.heartaxDetailModel.audio_src stringByReplacingOccurrencesOfString:@"\\" withString:@"/"];
        _strUrl = strUrl;
    }
    
    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];

    url = [self urlOfCurrentlyPlayingInPlayer:player];
    
    if ([url.absoluteString isEqualToString:_strUrl]) {
        
        CMTime time = player.currentItem.duration;
        Float64 durationSeconds = CMTimeGetSeconds(time);
        
        CMTime ctime = [player currentTime];
        Float64 currentSeconds = CMTimeGetSeconds(ctime);

        self.playDuration = [NSString stringWithFormat:@"%.2f",durationSeconds];
        self.cell.lbTotalTime.text = [self convertStringWithTime:([self.playDuration floatValue])];

        _cell1.lbtime.text = [NSString stringWithFormat:@"时长 %@",[self convertStringWithTime:([self.playDuration floatValue])]];
        self.playTime = [NSString stringWithFormat:@"%.2f",currentSeconds];

        self.progress = currentSeconds / durationSeconds;

        if ([WShareUtil sharedData].isPlay) {

            self.cell.lbPlayTime.text = [self convertStringWithTime:([self.playTime floatValue])];
            
            [self.cell.btnPlay setImage:[UIImage imageNamed:@"pause"] forState:UIControlStateNormal];
            self.cell.btnPlay.selected = YES;

            self.cell.sliderCell.enabled = YES;
            self.cell.sliderCell.minimumValue = 0;//设置最小值
            self.cell.sliderCell.maximumValue = 1;//设置最大值
            self.cell.sliderCell.value = self.progress;//设置默认值
            
            appDelegate.wWindow.playTool.lbTime.text = self.playTime;
            appDelegate.wWindow.playTool.lbPlayTit.titleStr = self.heartaxDetailModel.title;
            [appDelegate.wWindow.playTool.lbPlayTit show];

            [appDelegate.wWindow.playTool.btnPlay setImage:[UIImage imageNamed:@"pauseList"] forState:UIControlStateNormal];
            appDelegate.wWindow.playTool.btnPlay.selected = YES;

        }
    }else {
        [self.cell.btnPlay setImage:[UIImage imageNamed:@"playDetail"] forState:UIControlStateNormal];
        self.cell.btnPlay.selected = NO;
        
        [appDelegate.wWindow.playTool.btnPlay setImage:[UIImage imageNamed:@"Toolplay"] forState:UIControlStateNormal];
        appDelegate.wWindow.playTool.btnPlay.selected = NO;
        
        if (url) {
            [WShareUtil sharedData].dicMplayTime[url] = [NSNumber numberWithDouble:self.progress];
        }
        
//        WLog(@"%@",[NSNumber numberWithDouble:self.progress]);
//        
//        WLog(@"%@",[WShareUtil sharedData].dicMplayTime);

    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    [self.navigationController popToRootViewControllerAnimated:YES];
}


@end
